<?php
/**
 * Module used for application debug
 *
 * @author André Silva
 */
class DebugMode implements IModule {
	public static function start($args) {
		if ($args) {
			set_error_handler(array('DebugMode','handleError'));
			set_exception_handler(array('DebugMode','handleException'));
		}
	}

	public static function finish() {

	}

	/**
	 * Handle php errors
	 * @param int $errno
	 * @param string $errstr
	 * @param string $errfile
	 * @param int $errline
	 */
	public static function handleError($errno, $errstr, $errfile, $errline ) {
		throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
	}

	/**
	 * Handle unexpected exceptions
	 * @param Exception $exception
	 */
	public static function handleException($exception) {
		header('HTTP/1.1 500 Internal Server Error');

		$show = 5;
		$template = file_get_contents(Cerberus::resolvePath('cerberus.template.exception', true).'.tpl');
		$version = $_SERVER['SERVER_SOFTWARE'];
		$fileName = $exception->getFile();
		$errorLine = $exception->getLine();
		$errorType = get_class($exception);
		$errorMessage = htmlspecialchars($exception->getMessage());
		$lines = file($fileName);
		$beginLine = $errorLine - $show >= 0 ? $errorLine - $show - 1 : 0;
		$endLine = $errorLine + $show <= count($lines) ? $errorLine + $show : count($lines);

		$source = '';
		for ($i = $beginLine; $i < $endLine; $i++) {
			if ($i === $errorLine - 1) {
				$line = htmlspecialchars(sprintf("%04d: %s", $i + 1, str_replace("\t", '    ', $lines[$i])));
				$source .= "<span class=\"error\">" . $line . "</span>";
			}
			else {
				$source .= htmlspecialchars(sprintf("%04d: %s", $i + 1, str_replace("\t", '    ', $lines[$i])));
			}
		}

		$tokens = array();
		$tokens['%%ErrorType%%'] = $errorType;
		$tokens['%%ErrorMessage%%'] = $errorMessage;
		$tokens['%%SourceFile%%'] = htmlspecialchars($fileName);
		$tokens['%%SourceLine%%'] = $errorLine;
		$tokens['%%SourceCode%%'] = $source;
		$tokens['%%StackTrace%%'] = htmlspecialchars($exception->getTraceAsString());
		$tokens['%%Version%%'] = $version;
		$tokens['%%Time%%'] = strftime('%Y-%m-%d %H:%M:%S');

		echo strtr($template, $tokens);
	}
}
?>
